package mgobson

import (
	"fmt"
	"log"
	"time"

	"gitee.com/Flearning/go_crawl/setting"

	"gopkg.in/mgo.v2"
)

var (
	MgoDialInfo *mgo.DialInfo
	MgoSession  *mgo.Session
)

// 初始化mgo
func NewInit(imgo *setting.MgoInfo) {
	MgoDialInfo = &mgo.DialInfo{
		Addrs:    []string{imgo.Hosts},
		Timeout:  60 * time.Second,
		Database: imgo.Database,
		Username: imgo.UserName,
		Password: imgo.Password,
	}
	if MgoSession == nil {
		var err error
		MgoSession, err = MgoDial()
		if err != nil {
			fmt.Println(err)
		}
	}

	MgoSession.Clone()
}

func MgoDial() (*mgo.Session, error) {
	mgoSession, err := mgo.DialWithInfo(MgoDialInfo)
	if err != nil {
		log.Fatalf("CreateSession: %s\n", err)
	} else {
		mgoSession.SetMode(mgo.Monotonic, true)
	}
	return mgoSession, err
}

func CopyMgoConn() *mgo.Session {
	return MgoSession.Copy()
}

func WatchCollection(collection string, s func(*mgo.Collection) error) error {
	c := MgoSession.DB(MgoDialInfo.Database).C(collection)
	return s(c)
}
